package com.bjpowernode.core;

import com.bjpowernode.constant.Constant;
import com.bjpowernode.util.HttpUtils;
import com.bjpowernode.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;

/**
 * 分块下载类(实现Callable是未了确定是否下载成功)
 */
public class DownloaderTask implements Callable {

    //下载链接
    private String url;
    //起始位置
    private Long startPos;
    //结束位置
    private Long endPos;
    //标识第几块
    private int part;

    public DownloaderTask(String url, int part, Long startPos, Long endPos) {
        this.url = url;
        this.part = part;
        this.endPos = endPos;
        this.startPos = startPos;
    }

    @Override
    public Object call() throws Exception {
        //获取文件名
        String fileName = HttpUtils.getFileName(url);
        //分块的文件名
        fileName = fileName + "_" + part;
        //下载路径
        fileName = Constant.PATH + fileName;

        //获取分块下载的链接
        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url, startPos, endPos);

        try(
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                RandomAccessFile accessFile = new RandomAccessFile(fileName, "rw");
                ) {

            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len = -1;
            //循环读取数据
            while ((len = bis.read(buffer)) != -1){
                //1秒下载数据之和,通过原子类累加
                DownloadInfoThread.downSize.add(len);
                accessFile.write(buffer, 0, len);
            }
        }catch (FileNotFoundException e){
            LogUtils.error("文件不存在");
            return false;
        }catch (Exception e){
            LogUtils.error("下载失败");
            return false;
        }finally {
            httpURLConnection.disconnect();
        }
        return true;
    }
}
